package Fanshe;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorDemo {
@Test//获取各种构造器
    public void test() throws ClassNotFoundException, NoSuchMethodException {
    //获取当前类得字节码对象
    Class<?> aClass = Class.forName("Fanshe.Student");
    //获取公共无参构造器
    Constructor<?> constructor =aClass.getConstructor();
    System.out.println("我是无参构造器"+constructor);
    System.out.println("---------------------------");
    //获取公共有参构造器
    Constructor<?> constructor1 = aClass.getConstructor(Integer.class, String.class, String.class);
    System.out.println("我是有参构造器"+constructor1);
    System.out.println("--------------------------------");
    //获取私有构造器
    Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
    System.out.println("我是私有构造器"+declaredConstructor);
}
    @Test
            public void Test1() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    //获取当前类得字节码
        Class<?> aClass = Class.forName("Fanshe.Student");
        //公共无参构造器创建对象
        Constructor<?> constructor = aClass.getConstructor();
        Student o = (Student)constructor.newInstance();
        System.out.println(o);
        System.out.println("---------");
        //公共有参构造器创建对象
       // Constructor<?> constructor1 = aClass.getConstructor(Integer.class,String.class,String.class);
       // Student o1 = (Student)constructor1.newInstance(18,"张三","李四");
        //System.out.println(o1);
        //私有有参构造器创建对象
      //  Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
        //注 私有构造器不能创建对象，如果非要创建需要暴力解决
        //-void setAccessible(true)
//        declaredConstructor.setAccessible(true);
//        Student s =(Student) declaredConstructor.newInstance("迪丽热巴");
//        System.out.println(s);

    }

}
